package cn.edu.hunau.filter;


import cn.edu.hunau.pojo.User;
import cn.edu.hunau.utils.JsonUtils;
import cn.edu.hunau.utils.R;
import cn.edu.hunau.utils.ResultCodeEnum;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**

 * @Author 苏佳
 * @Date 2022 10 23 11 44
 **/
@WebFilter(value = {"*.order","*.user"})
public class Filter02CheckUsernameLoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        String servletPath = req.getServletPath();
        PrintWriter out = resp.getWriter();
        if(servletPath.contains("login")||servletPath.contains("regist")||servletPath.contains("checkUsername")){
            chain.doFilter(req,resp);
        }else {
            HttpSession session = req.getSession();
            User username = (User) session.getAttribute("LOGIN_USER");
            if(Objects.isNull(username)){
                //说明没有登录
                //TODO:异步处理时需要修改
                //resp.sendRedirect("login.html");
                out.println(JsonUtils.objectToJson(R.setResult(ResultCodeEnum.USER_HASNOT_LOGIN)));
            }else {
                chain.doFilter(req,resp);
            }
        }
    }
}
